
#include "delay.h"
#include "printf.h"
#include <stdbool.h>
#include <stdio.h>
#include <stm32f10x.h>

typedef unsigned short u16;

void TIM2_PWM1_init(u16 prescaler, u16 period) {

    GPIO_InitTypeDef GPIOA_initial;
    TIM_TimeBaseInitTypeDef TIM2_initial;
    TIM_OCInitTypeDef TIM2_PWM_initial;

    // TIM2 channel2 and AFIO settings
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO | RCC_APB2Periph_GPIOA, ENABLE);

    GPIOA_initial.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_2;
    GPIOA_initial.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIOA_initial.GPIO_Speed = GPIO_Speed_50MHz;

    GPIO_Init(GPIOA, &GPIOA_initial);

    // VCC A2
    GPIO_WriteBit(GPIOA, GPIO_Pin_2, Bit_SET);
    // GND A0
    GPIO_WriteBit(GPIOA, GPIO_Pin_0, Bit_RESET);

    // A1 舵机
    GPIOA_initial.GPIO_Pin = GPIO_Pin_1;
    GPIOA_initial.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIOA_initial.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIOA_initial);

    // TIM2 APB1PeriphClock
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);

    TIM2_initial.TIM_CounterMode = TIM_CounterMode_Up;
    TIM2_initial.TIM_Prescaler = prescaler - 1;
    TIM2_initial.TIM_Period = period - 1;

    TIM_TimeBaseInit(TIM2, &TIM2_initial);

    // pwm settings
    // OC output compare

    TIM2_PWM_initial.TIM_OCMode = TIM_OCMode_PWM1;
    TIM2_PWM_initial.TIM_OutputState = TIM_OutputState_Enable;
    TIM2_PWM_initial.TIM_OCPolarity = TIM_OCPolarity_High;
    TIM2_PWM_initial.TIM_Pulse = 50;

    TIM_OC2Init(TIM2, &TIM2_PWM_initial);

    TIM_Cmd(TIM2, ENABLE);
    // SystemCoreClock 72MHz
}

int main() {

    printf_init(9600);
    delay_init();
    // T=20ms f=50Hz
    TIM2_PWM1_init(7200, 200);

    while (true) {

        printf("main running\r\n");
        TIM_SetCompare2(TIM2, 0.5 * 10);
        delay_s(2);
        TIM_SetCompare2(TIM2, 2.5 * 10);
        delay_s(2);
    }

    return 0;
}
